﻿using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Sensors;
using Microsoft.Xna.Framework;

namespace CaptureAccelerometerData
{
    public partial class MainPage : PhoneApplicationPage
    {
        Accelerometer _ac;

        public MainPage()
        {
            InitializeComponent();
            
            _ac = new Accelerometer();
            _ac.CurrentValueChanged+=new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(_ac_CurrentValueChanged); 
		}

		private void _ac_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
		{
			// Invoke accelerometer reading in current UI thread in order to be
			// able to update UIElements
			Deployment.Current.Dispatcher.BeginInvoke(() => ProcessAccelerometerReading(e));
		}

		private void ProcessAccelerometerReading(SensorReadingEventArgs<AccelerometerReading> e)
        {
			Vector3 reading = e.SensorReading.Acceleration;
			
			txtTime.Text = e.SensorReading.Timestamp.ToString();
			txtX.Text = reading.X.ToString();
			txtY.Text = reading.Y.ToString();
			txtZ.Text = reading.Z.ToString();
			txtPitch.Text = RadianToDegree((Math.Atan(reading.X / Math.Sqrt(Math.Pow(reading.Y, 2) + Math.Pow(reading.Z, 2))))).ToString();
			txtRoll.Text = RadianToDegree((Math.Atan(reading.Y / Math.Sqrt(Math.Pow(reading.X, 2) + Math.Pow(reading.Z, 2))))).ToString();
			txtYaw.Text = RadianToDegree((Math.Atan(Math.Sqrt(Math.Pow(reading.X, 2) + Math.Pow(reading.Y, 2)) / reading.Z))).ToString();
        }

        private double RadianToDegree(double radian)
        {
            return radian * (180.0 / Math.PI);
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _ac.Start();
            }
            catch (AccelerometerFailedException)
            {
                MessageBox.Show("Acceleromter failed to start.");
            }
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _ac.Stop();
            }
            catch (AccelerometerFailedException)
            {
                MessageBox.Show("Acceleromter failed to stop.");
            }
        }
    }
}
